package com.fanjia.rabbitmq_java.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author fanjia
 * @className Producer
 * @description TODO
 * @date 2021/4/17 15:04
 */
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //tcp/ip amqp是再tcp/ip再次封装的一种消息协议

        //1.创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.130.114");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");//把我们的消息发在根目录下。

        Connection connection = null;
        Channel channel = null;
        //2.创建连接 connection
        connection = connectionFactory.newConnection("生产者");
        //3.通过连接获取通道channel
        channel = connection.createChannel();



        //5.准备消息内容
        String message = "Hello rabbitmq";

        //6. 准备交换机
        String exchangeName = "fanout-exchange";
        //7.定义路由key
        String routeKey="";
        //8. 指定交换机类型
        String type = "fanout";

        //6.发送消息给队列 queue
        channel.basicPublish(exchangeName,routeKey,null,message.getBytes());
        System.out.println("发送消息成功");
        //7.关闭连接
        if(connection != null && connection.isOpen()){
            connection.close();
        }

        //8.关闭通道
        if(channel != null && channel.isOpen()){
            channel.close();
        }

    }
}
